<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/praise_functions.php';
require_once 'login_check.php';
require_once 'manage_index.php';
session_start();
check_admin_session();

// 管理页面参数（区分奖励/批评管理）
$manage = isset($_GET['manage']) ? intval($_GET['manage']) : 1;

// 批量操作处理
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    global $pdo;

    // 批量修改
    if ($action === 'batch_edit' && !empty($_POST['edit_ids'])) {
        foreach ($_POST['edit_ids'] as $id) {
            $title = $_POST['title'][$id] ?? '';
            $content = $_POST['content'][$id] ?? '';
            $type = $_POST['type'][$id] ?? '';
            if (!in_array($type, ['praise', 'criticism']))
                continue;
            $display_order = $_POST['display_order'][$id] ?? 0;
            $is_active = isset($_POST['is_active'][$id]) ? 1 : 0;
            $stmt = $pdo->prepare("UPDATE praises SET title=?, content=?, type=?, display_order=?, is_active=? WHERE id=?");
            $stmt->execute([$title, $content, $type, intval($display_order), $is_active, intval($id)]);
        }
        header("Location: praise_manage.php?manage=$manage");
        exit;
    }
    // 批量展示
    elseif ($action === 'batch_show' && !empty($_POST['edit_ids'])) {
        foreach ($_POST['edit_ids'] as $id) {
            $stmt = $pdo->prepare("UPDATE praises SET is_active=1 WHERE id=?");
            $stmt->execute([intval($id)]);
        }
        header("Location: praise_manage.php?manage=$manage");
        exit;
    }
    // 批量停止展示
    elseif ($action === 'batch_hide' && !empty($_POST['edit_ids'])) {
        foreach ($_POST['edit_ids'] as $id) {
            $stmt = $pdo->prepare("UPDATE praises SET is_active=0 WHERE id=?");
            $stmt->execute([intval($id)]);
        }
        header("Location: praise_manage.php?manage=$manage");
        exit;
    }
    // 批量删除
    elseif ($action === 'batch_delete' && !empty($_POST['edit_ids'])) {
        $ids = array_map('intval', $_POST['edit_ids']);
        $in = implode(',', $ids);
        $pdo->exec("DELETE FROM praises WHERE id IN ($in)");
        header("Location: praise_manage.php?manage=$manage");
        exit;
    }
    // 添加新记录
    elseif ($action === 'add') {
        $title = $_POST['title'] ?? '';
        $content = $_POST['content'] ?? '';
        $type = $_POST['type'] ?? '';
        $display_order = $_POST['display_order'] ?? 0;
        $is_active = isset($_POST['is_active']) ? 1 : 0;

        if (!empty($title) && !empty($content) && in_array($type, ['praise', 'criticism'])) {
            $stmt = $pdo->prepare("INSERT INTO praises (title, content, type, display_order, is_active) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$title, $content, $type, intval($display_order), $is_active]);
        }
        header("Location: praise_manage.php?manage=$manage");
        exit;
    }
}

// 单条增删改处理
handle_praise_actions();

// 获取所有数据用于管理
$allPraises = get_all_praises();
?>

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>奖惩管理</title>
    <!-- Google Fonts for Modern Look -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
    <!-- Modern Icons -->
    <style>
        body {
            font-family: 'Inter', 'Segoe UI', 'Helvetica Neue', Arial, 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background: #f5f7fa;
            margin: 0;
            display: flex;
            min-height: 100vh;
        }

        .main-content {
            margin-left: 240px;
            width: 100%;
            padding: 48px 32px 32px 32px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .card {
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 4px 18px rgba(41, 128, 255, 0.08);
            margin-bottom: 36px;
            width: 100%;
            max-width: 1000px;
            padding: 32px;
            display: flex;
            flex-direction: column;
            align-items: stretch;
            transition: box-shadow 0.2s;
        }

        .card:hover {
            box-shadow: 0 8px 24px rgba(41, 128, 255, 0.12);
        }

        .card-title {
            font-size: 1.45em;
            font-weight: bold;
            color: #000000;
            margin-bottom: 24px;
            letter-spacing: 1.5px;
            display: flex;
            align-items: center;
        }

        .card-title.criticism {
            color: #000000;
        }

        .card-title .mdi {
            font-size: 1.5em;
            margin-right: 12px;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 12px;
            table-layout: fixed;
            font-size: 1em;
        }

        .table th,
        .table td {
            padding: 12px 14px;
            border-bottom: 1px solid #eaeaea;
            text-align: left;
            word-break: break-all;
        }

        .table th {
            background: #f0f5ff;
            color: #2980ff;
            font-weight: 700;
            letter-spacing: 1px;
            border-bottom: 2px solid #2980ff;
        }

        .table th:first-child,
        .table td:first-child {
            width: 50px;
            text-align: center;
        }

        .table th:nth-child(2) {
            width: 60px;
        }

        .table th:nth-child(3),
        .table th:nth-child(4) {
            width: 25%;
        }

        .table th:nth-child(5) {
            width: 120px;
        }

        .table th:nth-child(6),
        .table th:nth-child(7) {
            width: 100px;
        }

        .table tr:last-child td {
            border-bottom: none;
        }

        .table tr.inactive {
            color: #aaa;
        }

        .table input[type="text"],
        .table input[type="number"],
        .table select {
            width: 100%;
            padding: 6px 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-family: inherit;
            font-size: 0.95em;
        }

        .table input[type="checkbox"] {
            width: 18px;
            height: 18px;
        }

        .add-form {
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
            margin-bottom: 24px;
            align-items: center;
        }

        .add-form label {
            display: flex;
            align-items: center;
            gap: 6px;
            white-space: nowrap;
        }

        .add-form input[type="text"],
        .add-form input[type="number"] {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-family: inherit;
            font-size: 1em;
        }

        .add-form input[name="title"] {
            width: 200px;
        }

        .add-form input[name="content"] {
            width: 300px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            font-family: inherit;
            font-size: 1em;
            cursor: pointer;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .btn .mdi {
            font-size: 1.1em;
        }

        .btn-primary {
            background: #2980ff;
            color: white;
        }

        .btn-primary:hover {
            background: #1866d1;
        }

        .btn-success {
            background: #43b362;
            color: white;
        }

        .btn-success:hover {
            background: #35924c;
        }

        .btn-neutral {
            background: #888;
            color: white;
        }

        .btn-neutral:hover {
            background: #666;
        }

        .btn-danger {
            background: #ff4d4f;
            color: white;
        }

        .btn-danger:hover {
            background: #d9363e;
        }

        .actions {
            display: flex;
            gap: 12px;
            margin-top: 20px;
            justify-content: flex-start;
        }

        .no-data {
            text-align: center;
            color: #888;
            font-size: 1.05em;
            padding: 30px 0;
        }

        .nav-links {
            align-self: flex-start;
            margin-bottom: 24px;
            display: flex;
            gap: 16px;
        }

        .nav-links a {
            color: #2980ff;
            text-decoration: none;
            padding: 6px 12px;
            border-radius: 4px;
            transition: background 0.2s;
        }

        .nav-links a:hover {
            background: #f0f5ff;
        }

        @media (max-width: 1200px) {
            .main-content {
                padding: 32px 24px;
            }

            .card {
                padding: 24px;
            }
        }

        @media (max-width: 900px) {
            
            .card {
                max-width: 99vw;
                padding: 16px;
            }

            .table th:nth-child(3),
            .table th:nth-child(4) {
                width: 20%;
            }
        }

        @media (max-width: 600px) {
            .main-content {
                padding: 16px 8px;
            }

            .card {
                padding: 12px;
            }

            .add-form {
                flex-direction: column;
                align-items: stretch;
            }

            .add-form input[name="title"],
            .add-form input[name="content"] {
                width: 100%;
            }

            .actions {
                flex-wrap: wrap;
            }

            .btn {
                flex: 1;
                min-width: 120px;
            }

            .table th:nth-child(5),
            .table th:nth-child(6) {
                display: none;
            }

            .table td:nth-child(5),
            .table td:nth-child(6) {
                display: none;
            }
        }
    </style>
</head>

<body>
    <?php render_sidebar(); ?>    
    <div class="main-content">
        <div class="card">
            <div class="card-title <?= $manage == 2 ? 'criticism' : '' ?>">
                <span class="mdi <?= $manage == 1 ? 'mdi-trophy-award' : 'mdi-alert-circle' ?>"></span>
                <?= $manage == 1 ? '奖励表彰管理' : '通报批评管理' ?>
            </div>

            <!-- 添加新记录表单 -->
            <form method="post" class="add-form">
                <input type="hidden" name="action" value="add">
                <input type="hidden" name="type" value="<?= $manage == 1 ? 'praise' : 'criticism' ?>">

                <label>
                    标题:
                    <input name="title" required placeholder="输入标题">
                </label>
                <label>
                    内容:
                    <input name="content" required style="width:300px;" placeholder="输入内容">
                </label>
                <label>
                    排序:
                    <input type="number" name="display_order" value="0" min="0">
                </label>
                <label>
                    展示:
                    <input type="checkbox" name="is_active" checked>
                </label>
                <button class="btn btn-primary" type="submit">
                    <span class="mdi mdi-plus"></span>添加
                </button>
            </form>

            <!-- 批量编辑/展示/隐藏/删除表单 -->
            <form method="post">
                <table class="table">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="allCheck" onclick="toggleAll(this)"></th>
                            <th>ID</th>
                            <th>标题</th>
                            <th>内容</th>
                            <th>类型</th>
                            <th>排序</th>
                            <th>展示</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $filtered = array_filter($allPraises, function ($row) use ($manage) {
                            return ($manage == 1 && $row['type'] === 'praise') ||
                                ($manage == 2 && $row['type'] === 'criticism');
                        });

                        if (empty($filtered)):
                            ?>
                            <tr>
                                <td colspan="7" class="no-data">暂无记录</td>
                            </tr>
                        <?php else:
                            foreach ($filtered as $row):
                                ?>
                                <tr<?= !$row['is_active'] ? ' class="inactive"' : '' ?>>
                                    <td>
                                        <input type="checkbox" name="edit_ids[]" value="<?= $row['id'] ?>">
                                    </td>
                                    <td><?= $row['id'] ?></td>
                                    <td>
                                        <input name="title[<?= $row['id'] ?>]" value="<?= htmlspecialchars($row['title']) ?>"
                                            required>
                                    </td>
                                    <td>
                                        <input name="content[<?= $row['id'] ?>]"
                                            value="<?= htmlspecialchars($row['content']) ?>" required>
                                    </td>
                                    <td>
                                        <select name="type[<?= $row['id'] ?>]">
                                            <option value="praise" <?= $row['type'] == 'praise' ? 'selected' : '' ?>>奖励表彰</option>
                                            <option value="criticism" <?= $row['type'] == 'criticism' ? 'selected' : '' ?>>通报批评
                                            </option>
                                        </select>
                                    </td>
                                    <td>
                                        <input type="number" name="display_order[<?= $row['id'] ?>]"
                                            value="<?= $row['display_order'] ?>" min="0">
                                    </td>
                                    <td>
                                        <input type="checkbox" name="is_active[<?= $row['id'] ?>]" <?= $row['is_active'] ? 'checked' : '' ?>>
                                    </td>
                                    </tr>
                                <?php endforeach; endif; ?>
                    </tbody>
                </table>

                <div class="actions">
                    <button class="btn btn-primary" type="submit" name="action" value="batch_edit"
                        onclick="return confirm('确定批量修改所选记录？')">
                        <span class="mdi mdi-pencil"></span>批量修改
                    </button>
                    <button class="btn btn-success" type="submit" name="action" value="batch_show"
                        onclick="return confirm('确定批量展示所选记录？')">
                        <span class="mdi mdi-eye"></span>批量展示
                    </button>
                    <button class="btn btn-neutral" type="submit" name="action" value="batch_hide"
                        onclick="return confirm('确定批量停止展示所选记录？')">
                        <span class="mdi mdi-eye-off"></span>批量停止展示
                    </button>
                    <button class="btn btn-danger" type="submit" name="action" value="batch_delete"
                        onclick="return confirm('确定批量删除所选记录？操作不可恢复！')">
                        <span class="mdi mdi-trash-can"></span>批量删除
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function toggleAll(src) {
            var cbs = document.querySelectorAll('input[name="edit_ids[]"]');
            for (let cb of cbs) {
                cb.checked = src.checked;
            }
        }
    </script>
</body>

</html>